package com.kindergarten.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kindergarten.pojo.Role;
import com.kindergarten.pojo.User;
import com.kindergarten.pojo.UserRole;
import com.kindergarten.service.IRoleService;
import com.kindergarten.service.IUserRoleService;
import com.kindergarten.service.IUserService;
import com.kindergarten.utils.DataResults;
import com.kindergarten.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 认证成功的处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserRoleService userRoleService;

    @Autowired
    IRoleService iRoleService;

    /**
     * 认证成功的处理器
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //  响应一段JSON UTF-8编码
        response.setContentType("application/json;charset=utf-8");
        //认证成功的对象
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String userId = userDetails.getUsername();

        //根据登录成功的userId查询user对象
        User user = iUserService.getById(userId);
        System.out.println("登录成功,登录对象是：" + user);

        UserRole user_role = userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id", userId));
        DataResults dataResults = null;
        if (user_role != null) {
            Integer roleId = user_role.getRoleId();
            // 角色对象
            Role role = iRoleService.getById(roleId);
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setAttribute("role", role);
            dataResults = DataResults.success(ResultCode.SUCCESS); //200
        }else{
            dataResults = DataResults.success(ResultCode.NO_RIGTHS); //403
        }
        // 人工转JSON
        String jsonResult = new ObjectMapper().writeValueAsString(dataResults);
        response.getWriter().write(jsonResult);

    }
}
